<?php

namespace addons\csmitsm\library\xcore\xcore\job;

use think\Config;
use app\common\library\Sms;
use addons\csmitsm\library\xcore\xcore\base\XcAJob;
use addons\csmitsm\library\xcore\xcore\XcException;
use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcConfigUtils;

class XcMessageNotifyJob extends XcAJob
{
    /**
     * 发送短信
         sendsms('17702162216', 'xcflow_mobiletpl', '审核通过', ['code' => $code]); 
     * @return void
     */
    public function sendsms($mobile, $configname, $tplname, $data)
    {
        $csmtpl = XcConfigUtils::config($configname);

        if (! array_key_exists($tplname, $csmtpl)) {
            throw new XcException($tplname . "模板不存在，请到插件管理中配置：" . XcConfigUtils::getAddonCode() . " - 短信模板({$tplname})");
        }

        $ret = Sms::notice($mobile, $data, $csmtpl[$tplname]);

        if ($ret === false) {
            throw new XcException('发送失败');
        }
    }
    /**
     * 发送验证码短信
         sendccodesms('17702162216', 'xcflow_mobiletpl', '1234', ['code' => $code]); 
     * @return void
     */
    public function sendccodesms($mobile, $configname, $event)
    {
        $code = mt_rand(1000, 9999);
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create([
            'event' => $event,
            'mobile' => $mobile,
            'code' => $code,
            'ip' => $ip,
            'createtime' => $time
        ]);

        $ret = static::sendsms($mobile, $configname, $event, [
            'code' => $code
        ]);

        if ($ret === false) {
            $sms->delete();
            throw new XcException('发送失败');
        }
    }

    public function sendemail($email, $configname, $title, $tplname, $data)
    {
        // 如果邮箱格式不对,则不发送邮件
        if (strpos($email, '@') === false) {
            return;
        }

        $csmtpl = XcConfigUtils::config($configname);
        if (! array_key_exists($tplname, $csmtpl)) {
            new XcException($tplname . "模板不存在，请到插件管理中配置：" . XcConfigUtils::xpconfig('addons_name') . " - 邮件模板({$tplname}):");
        }
        foreach ($data as $k => $v) {
            $$k = $v;
        }
        $contentdata = static::_formatTempalte($csmtpl[$tplname], $data);
        if ($email != null && $email != '') {
            $site = Config::get("site");
            $obj = \app\common\library\Email::instance();
            $ret = $obj->to($email)
                ->subject("[" . $site['name'] . "]" . $title)
                ->message($contentdata)
                ->send();
            if ($ret === false) {
                throw new XcException('发送失败');
            }
        }
    }

    private static function _formatTempalte($template, $data)
    {
        foreach ($data as $k => $v) {
            $template = str_replace("[[{$k}]]", $v, $template);
        }
        return $template;
    }

    /**
     * 消息通知管理员
         notifyAdmin(1, ["email"=>"xcflow_emailtpl", "mobile"=>"xcflow_mobiletpl"], "TPL消息模版", "这个是标题", ["code"=>"1234"]);
     * @return void
     */
    public function notifyAdmin($admin_id, $confignames, $tplname, $title, $data)
    {
        $row = XcDaoUtils::getRowById(new \app\admin\model\Admin(), $admin_id);
        if (! $row) {
            return;
        }

        $email_configname = $confignames['email'];
        if (!empty($row->email) && XcConfigUtils::isConfigEnable($email_configname)) {
            $this->sendemail($row->email, $email_configname, $title, $tplname, $data);
        }

        $mobile_configname = $confignames['mobile'];
        if (!empty($row->mobile) && XcConfigUtils::isConfigEnable($mobile_configname)) {
            $this->sendsms($row->mobile, $mobile_configname, $tplname, $data);
        }
    }

    /**
     * 消息通知管理员角色
     *
     * @return void
     */
    public static function notifyAdminRole($role_id, $confignames, $tplname, $title, $data)
    {
        $admingroups = XcDaoUtils::getListBySql(new \app\admin\model\AuthGroupAccess(), [['group_id', '=', $role_id]], null, null, false);
        foreach ($admingroups as $admingroup) {
            static::notifyAdmin($admingroup['uid'], $confignames, $tplname, $title, $data);
        }
    }
}
